package remote;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

import metadata.schema.Schema;

import represent.*;
import represent.expression.*;
class RemoteResultSetImpl extends UnicastRemoteObject implements RemoteResultSet {

	private static final long serialVersionUID = -8265070816919477152L;
	private Scan scan;
	private Schema sch;
	private RemoteConnectionImpl rconn;
	private List<Expression> exps;

	public RemoteResultSetImpl(Plan plan, List<Expression> exps
			, RemoteConnectionImpl rconn) throws RemoteException {
		scan = plan.open(null);
		sch = plan.schema();
		System.out.println("Final schema: \n" + sch);
		this.rconn = rconn;
		this.exps = exps;
	}

	public boolean next() throws RemoteException {
		try {
			return scan.next();
		}
		catch(RuntimeException e) {
			rconn.rollback();
			throw e;
		}
	}
	public Object getObject(int columnIndex) throws RemoteException {
		try {
			Expression e = exps.get(columnIndex - 1);
			return e.evaluate(scan).asJavaVal();
		} catch(RuntimeException e) {
			rconn.rollback();
			throw e;
		}
	}

	public RemoteMetaData getMetaData() throws RemoteException {
		return new RemoteMetaDataImpl(sch);
	}
	
	public void beforeFirst() throws RemoteException {
		try {
			scan.beforeFirst();
		} catch(RuntimeException e) {
			rconn.rollback();
			throw e;
		}
	}

	@Override
	public void close() throws RemoteException {
	      scan.close();
	      rconn.commit();
	   }
}
